package GUILayer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Iterator;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

import CtrLayer.ContractorCtr;
import ModelLayer.Contractor;

public class ContractorGUI {
	private JPanel panel;
	private JTable contractorTable;
	private Object[][] data;
	private int size;
	private static int idC = 1000;
	private static ContractorCtr contractorCtr = new ContractorCtr();
	
	public ContractorGUI() {
		
		
	}
	
	private JPanel makeGridListContractors() {
		Iterator<?> it = contractorCtr.getContractorIterator();
		size = contractorCtr.getContractorSize();
		
		String[] columnNames = { "ID", "Name", "Address", "Postal Code", "Phone", "E-mail", "Description", "Delete" };
		data = new Object[size][columnNames.length];
		
		int i = 0;
		while (it.hasNext()) {
			Contractor cont = (Contractor) it.next();
			data[i][0] = cont.getId();
			data[i][1] = cont.getName();
			data[i][2] = cont.getAddress();
			data[i][3] = cont.getPostCode();
			data[i][4] = cont.getPhone();
			data[i][5] = cont.getEmail();
			data[i][6] = cont.getDescription();
			data[i][7] = Boolean.FALSE;
			i++;
		}
		
		JPanel gridContractor = new JPanel();
		DefaultTableModel dtm = new DefaultTableModel(data, columnNames) {
			private static final long serialVersionUID = 1L;
			
			public boolean isCellEditable(int row, int col) {
				return (col == 7);
			}
			
			public Class<?> getColumnClass(int col) {
				if (col == 7)
					return Boolean.class;
				return super.getColumnClass(col);
			}
		};
		
		contractorTable = new JTable(dtm);
		contractorTable.getTableHeader().addMouseListener(new MouseListener() {
			public void mouseClicked(MouseEvent e) {
				int col = contractorTable.columnAtPoint(e.getPoint());
				if (col == 7) {
					if(Main.access==false)	
					{
						JOptionPane.showConfirmDialog(null, "You don't have access","Info",JOptionPane.CLOSED_OPTION);
						return;
					}
					
					int selected = getSelectedContractor(contractorTable);
					if (selected == 0) {
						JOptionPane.showConfirmDialog(null,
								"You didn't select any Contractors", "Info",
								JOptionPane.CLOSED_OPTION);
					} else {
						int answer = JOptionPane.showConfirmDialog(null,
								"Are you sure you want to delete " + selected
										+ " contractor(s)?", "Confirm delete",
								JOptionPane.YES_NO_OPTION);	
						if (answer == JOptionPane.YES_OPTION){
							deleteSelectedContractor(contractorTable);
						}
					} 
				}
			}
			
			@Override
			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseExited(MouseEvent arg0){
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mousePressed(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseReleased(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		TableColumnModel tcm = contractorTable.getColumnModel();
		tcm.getColumn(0).setPreferredWidth(40);
		
		JScrollPane contractorTableScroll = new JScrollPane(contractorTable);
		contractorTableScroll.setPreferredSize(new Dimension(500, 145));
		contractorTableScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		contractorTableScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		
		gridContractor.add(contractorTableScroll, BorderLayout.CENTER);
		
		contractorTable.addMouseListener(new MouseAdapter() {
			
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					JTable target = (JTable) e.getSource();
					int row = target.getSelectedRow();
					int idContractor = 0;
					try {
						idContractor = (Integer) target.getModel().getValueAt(
								row, 0);
						contractorFrame(idContractor);
					} catch (Exception ex) {
					}	
				}
			}
		});
		
		return gridContractor;
	}
	
	private JPanel makeAddContractorPanel() {
		JPanel addPanel = new JPanel();
		GridLayout grid = new GridLayout(0, 2);
		grid.setVgap(4);
		
		addPanel.setLayout(grid);
		
		String[] addContractorFields = { "Name", "Address", "Postal Code", "Phone", "E-mail", "Description" };
		final JTextField[] addContractorTextFields = new JTextField[7];
		
		for (int i = 0; i < addContractorFields.length; i++) {
			JLabel fieldL = new JLabel(addContractorFields[i]);
			addContractorTextFields[i] = new JTextField(15);
			
			addPanel.add(fieldL);
			addPanel.add(addContractorTextFields[i]);
		}
		
		JPanel errMess = new JPanel();
		final JLabel errors = new JLabel();
		errors.setForeground(Color.red);
		errMess.add(errors);
		
		JPanel addContractorMain = new JPanel();
		addContractorMain.setLayout(new BoxLayout(addContractorMain,
				BoxLayout.Y_AXIS));
		int sp = 7;
		addContractorMain.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createTitledBorder(
						BorderFactory.createLineBorder(Color.black),
						"Add Contractor"), BorderFactory.createEmptyBorder(sp,
								sp, sp, sp)));
		
		addContractorMain.add(addPanel);
		addContractorMain.add(errMess);
		
		JButton addContButton = new JButton("Add Customer");
		addContButton.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				String error = "";
				
				String name = addContractorTextFields[0].getText();
				String address = addContractorTextFields[1].getText();
				String postalCode = addContractorTextFields[2].getText();
				String phone = addContractorTextFields[3].getText();
				String email = addContractorTextFields[4].getText();
				String desc = addContractorTextFields[5].getText();
				
				if(name.isEmpty())
					error = "The Name field is empty";
				else if (address.isEmpty())
					error = "The Address field is empty";
				else if (postalCode.isEmpty())
					error = "The Postal Code field is empty";
				else if (phone.isEmpty())
					error = "The Phone no. field is empty";
				else if (email.isEmpty())
					error = "The Email field is empty";
				else if (desc.isEmpty())
					error = "The Description field is empty";
				
				if (error != "") {
					errors.setText(error);
				} else {
					errors.setText("");
					contractorCtr.createContractor(idC, name, address, postalCode, phone, email, desc);
					idC++;
					reAddGrid();
				}
			}
			
		});
		
		addPanel.add(new JLabel());
		addPanel.add(addContButton);
		
		return addContractorMain;
		
	}
	
	private void contractorFrame(int idC) {
		
		final JFrame frame = new JFrame("Contractor ID: " + idC);
		JPanel mainPanel = new JPanel();
		
		try {
			final Contractor contractor = contractorCtr.getContractor(idC);
			
			JLabel labID = new JLabel("Id");
			JLabel labName = new JLabel("Name");
			JLabel labAddress = new JLabel("Address");
			JLabel labPostalCode = new JLabel("Postal Code");
			JLabel labPhone = new JLabel("Phone Number");
			JLabel labEmail = new JLabel("Email");
			JLabel labDesc = new JLabel("Description");
			
			int cols = 6;
			JLabel llab1 = new JLabel();
			
			final JTextField textID = new JTextField(cols);
			final JTextField textName = new JTextField(cols);
			final JTextField textAddress = new JTextField(cols);
			final JTextField textPostalCode = new JTextField(cols);
			final JTextField textPhone = new JTextField(cols);
			final JTextField textEmail = new JTextField(cols);
			final JTextField textDesc = new JTextField(cols);
			
			textID.setText(String.valueOf(contractor.getId()));
			textName.setText(contractor.getName());
			textAddress.setText(contractor.getAddress());
			textPostalCode.setText(contractor.getPostCode());
			textPhone.setText(contractor.getPhone());
			textEmail.setText(contractor.getEmail());
			textDesc.setText(contractor.getDescription());
			
			JPanel grid1 = new JPanel();
			JPanel grid2 = new JPanel();
			JPanel grid3 = new JPanel();

			GridLayout gridLay = new GridLayout(0, 2);
			GridLayout gridLay3 = new GridLayout(0, 2);

			gridLay3.setHgap(20);

			grid1.setLayout(gridLay);
			grid2.setLayout(gridLay);
			grid3.setLayout(gridLay3);

			grid1.add(labID);
			grid1.add(textID);

			grid1.add(labName);
			grid1.add(textName);

			grid1.add(labAddress);
			grid1.add(textAddress);

			grid1.add(labPostalCode);
			grid1.add(textPostalCode);

			grid2.add(labPhone);
			grid2.add(textPhone);

			grid2.add(labEmail);
			grid2.add(textEmail);

			grid2.add(labDesc);
			grid2.add(textDesc);
			
			grid3.add(grid1);
			grid3.add(grid2);

			JPanel buttonPanel = new JPanel();
			JButton addButton = new JButton("Save");
			JButton deleteButton = new JButton("Cancel");

			buttonPanel.add(addButton);
			buttonPanel.add(deleteButton);

			deleteButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent ev) {
					frame.setVisible(false);

				}
			});
			
			addButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {

					String name = textName.getText();
					String address = textAddress.getText();
					String postalCode = textPostalCode.getText();
					String phone = textPhone.getText();
					String email = textEmail.getText();
					String desc = textDesc.getText();
					
					if (name.isEmpty())
						popupError("Name field is empty");
					else if (address.isEmpty())
						popupError("Address field is empty");
					else if (postalCode.isEmpty())
						popupError("Postal Code field is empty");
					else if (phone.isEmpty())
						popupError("Phone number field is empty");
					else if (email.isEmpty())
						popupError("Email field is empty");
					else if (desc.isEmpty())
						popupError("Description field is empty");
					else {
						int answer = JOptionPane.showConfirmDialog(frame,
								"Do you wish to save? ", "Confirm saving",
								JOptionPane.YES_NO_OPTION);

						if (answer == JOptionPane.YES_OPTION) {
							contractor.setName(name);
							contractor.setAddress(address);
							contractor.setPostCode(postalCode);
							contractor.setPhone(phone);
							contractor.setEmail(email);
							contractor.setDescription(desc);
							
							frame.setVisible(false);
							reAddGrid();

						}
					}
				}
			});
			mainPanel.add(grid3);
			mainPanel.add(buttonPanel);
			
		} catch (Exception e) {
			
		}
		
		frame.setContentPane(mainPanel);
		frame.setSize(new Dimension(400, 300));
		frame.setResizable(false);
		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		frame.setVisible(true);
		frame.setLocationRelativeTo(null);
	}
	
	private void reAddGrid() {
		try{
			panel.remove(1);
			panel.add(makeGridListContractors());
			panel.revalidate();	
		}catch(Exception ex){}
	}
	
	private void popupError(String message) {
		JOptionPane.showMessageDialog(null, message, "Error",
				JOptionPane.INFORMATION_MESSAGE);
	}
	
	private JPanel makeSearchPanel() {
		JPanel panel = new JPanel();
		int sp = 7;
		panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "Search"),BorderFactory.createEmptyBorder(sp, sp, sp, sp)));
		
		
		JLabel labSearch = new JLabel("ID or Name ");
		final JTextField textSearch = new JTextField(10);
		JButton searchButton = new JButton("Search");

		searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ev) {
				
				try {
					String search = textSearch.getText();
					
					int rowHigh = -1;
					for (int i = 0; i < size; i++)
						if (data[i][0].toString().equals(search) || (data[i][1]).toString().equals(search)) {
							rowHigh = i;
							break;
						}
					
					if (rowHigh >= 0) {
						contractorTable.setRowSelectionInterval(rowHigh, rowHigh);
						contractorTable.scrollRectToVisible(contractorTable.getCellRect(rowHigh, 0, true));
					}
				} catch (Exception ex) {
				}	
			}
			
		});
		
		panel.add(labSearch);
		panel.add(textSearch);
		panel.add(searchButton);

		return panel;
	}
	
	public JPanel makeContractorTab(){
		panel = new JPanel();
		JPanel fourthPanel = new JPanel();
		fourthPanel.add(makeSearchPanel());
		fourthPanel.add(makeAddContractorPanel());
		
		
		panel.add(fourthPanel);
		panel.add(makeGridListContractors());
		
		return panel;
	}
	
	private int getSelectedContractor(JTable table) {
		int count = 0;
		for (int i = 0; i < table.getRowCount(); i++) {
			if ((Boolean) table.getValueAt(i, 7) == true)
				count++;
		}
		return count;
	}
	
	private void deleteSelectedContractor(JTable table) {
		for (int i = 0; i < table.getRowCount(); i++) {
			if ((Boolean) table.getValueAt(i, 7) == true) {
				int contractorId = (Integer) table.getValueAt(i, 0);
				contractorCtr.deleteContractor(contractorId);
			}
		}
		reAddGrid();
	}
}
